<template>
  <div>
    <div style="display:flex;flex-direction:row-reverse;margin-top:10px">
      <el-button :loading="saveLoading" size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>
    <div style="margin-top:20px" class="qup-title-box"><span class="border" /><span>卖场测绘详情</span></div>
    <map-detail :detail-data="id" />
    <c-section title="测绘安排">
      <c-list :column="3">
        <c-list-item label="测量人类型" dict-type-code="SURVEYOR_TYPE" :value="detailData.surveyorType" />
        <c-list-item label="测量人姓名" :value="detailData.surveyorName" />
        <c-list-item label="测量人电话" :value="detailData.surveyorPhone" />
        <c-list-item label="预计测量时间" :value="detailData.expectSurveyTime" />
      </c-list>
    </c-section>
    <div class="qup-title-box"><span class="border" /><span>测绘执行</span></div>
    <el-form
      ref="refForm"
      :rules="formRules"
      :model="formData"
      size="mini"
      label-width="150px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="是否完成测绘:" prop="isFinishMapping">
            <el-select v-model="formData.isFinishMapping" placeholder="请选择">
              <el-option label="是" :value="1" />
              <el-option label="否 " :value="0" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row v-show="formData.isFinishMapping===1">
        <el-col :span="8">
          <el-form-item :rules="[{required:false,message:'请选择'}]" label="实际测量时间:" prop="actualSurveyTime">
            <el-date-picker
              v-model="formData.actualSurveyTime"
              type="date"
              size="mini"
              disabled
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :rules="[{required:formData.isFinishMapping&&detailData.marketType==='NEW_MARKET',message:'请填写'},
                     { pattern: /^([0-9]\d*)$/, message: '只能输入正整数' }]"
            label="测量卖场面积:"
            prop="surveyShopArea"
          >
            <el-input v-model.number="formData.surveyShopArea" :disabled="detailData.marketType!=='NEW_MARKET'" maxlength="4">
              <span slot="suffix">㎡</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="isDoorInclude" :span="8">
          <el-form-item :rules="[{required:formData.isFinishMapping&&isDoorInclude,message:'请填写'}]" label="测量门头面积:" prop="surveyDheaderArea">
            <el-input v-model.number="formData.surveyDheaderArea" maxlength="4">
              <span slot="suffix">㎡</span>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item :rules="[{required:formData.isFinishMapping,message:'请填写'}]" label="可吊顶最低高度:" prop="ceilingMinHeight">
            <el-input v-model="formData.ceilingMinHeight" type="number" @change="changeMinHeigh">
              <span slot="suffix">m</span>
            </el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row v-show="formData.isFinishMapping===1">
        <el-col v-show="isNeedRefeshArea" :span="8">
          <el-form-item
            :rules="[{required:formData.isFinishMapping&&isNeedRefeshArea,message:'请填写'},
                     { pattern: /^([0-9]\d*)$/, message: '只能输入正整数' }]"
            label="测量翻新面积:"
            prop="surveyRefurbishArea"
          >
            <el-input v-model.number="formData.surveyRefurbishArea" maxlength="4" @input="changeShopArea">
              <span slot="suffix">㎡</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="isNeedExtendArea" :span="8">
          <el-form-item
            :rules="[{required:formData.isFinishMapping&&isNeedExtendArea,message:'请填写'},
                     { pattern: /^([0-9]\d*)$/, message: '只能输入正整数' }]"
            label="测量扩建面积:"
            prop="surveyExpansionArea"
          >
            <el-input v-model.number="formData.surveyExpansionArea" maxlength="4" @input="changeShopArea">
              <span slot="suffix">㎡</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :rules="[{required:formData.isFinishMapping,message:'请选择'}]" label="是否需要复尺:" prop="isNeedResurvey">
            <el-select v-model="formData.isNeedResurvey" placeholder="请选择">
              <el-option label="是" :value="1" />
              <el-option label="否 " :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="formData.isFinishMapping&&formData.isNeedResurvey===0">
        <el-col :span="24">
          <el-form-item :rules="[{required:formData.isFinishMapping&&formData.isNeedResurvey===0,message:'请填写不复尺原因'}]" label="不复尺原因:" prop="unresurveyReason">
            <el-input v-model="formData.unresurveyReason" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="formData.isFinishMapping===0">
        <el-col :span="24">
          <el-form-item :rules="[{required:!formData.isFinishMapping,message:'请填写'}]" label="未测绘原因:" prop="unsurveyReason">
            <el-input v-model="formData.unsurveyReason" maxlength="1000" show-word-limit type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="qup-title-box"><span class="border" /><span>附件管理</span></div>
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="附件上传" name="first">
        <el-button size="mini" type="primary" @click.native="handleAddFile">新增</el-button>
        <el-button size="mini" type="primary" @click="handleDelete">删除</el-button>
        <file-detail
          type="selection"
          style="margin-top:20px"
          :file-data="fileDataList"
          @select="getSelectData"
          @change="changeFile"
        />
        <add-file v-if="showFileAdd" ref="formDlg" attachment-type="测绘结果" :visible.sync="showFileAdd" @success="onSuccess" />
      </el-tab-pane>
      <el-tab-pane label="附件查看" name="second">
        <file-detail style="margin-top:20px" :file-data="otherFileList" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import fileDetail from '../fileDetail.vue'
import addFile from '../fileAddDlg.vue'
import mapDetail from '../mapDetail.vue'
import { getShopAttachment } from '@/api/common.js'
import { getDetailData, saveState } from '@/api/shopMap'
import BackPageMixin from '@/mixins/backPage'
import CSection from '../../../../components/CSection/CSection.vue'
import { nowTime } from '@/utils/tool'

export default {
  name: 'MapExe',
  components: { addFile, mapDetail, fileDetail, CSection },
  mixins: [BackPageMixin],
  props: { },
  data() {
    return {
      id: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        } },
      activeName: 'first',
      nowTime,
      saveLoading: false,
      showFileAdd: false,
      isDoorInclude: false,
      isNeedRefeshArea: false,
      isNeedExtendArea: false,
      marketType: '',
      detailData: {}, // 测绘详情
      fileList: [], // 选择的行数据
      fileDataList: [], // 附件列表信息
      deleteFile: [],
      otherFileList: [],
      fileLength: 0, // 附件长度
      formData: {
        id: '',
        constCode: '',
        state: '',
        isFinishMapping: undefined,
        actualSurveyTime: '',
        unresurveyReason: '', // 不复尺原因
        surveyShopArea: 0,
        ceilingMinHeight: undefined,
        surveyDheaderArea: 0,
        surveyRefurbishArea: 0,
        surveyExpansionArea: 0,
        isNeedResurvey: 0,
        unsurveyReason: '',
        shopAttachmentDTOList: []// 附件信息
      },
      formRules: {
        isFinishMapping: [
          { required: true, message: '请选择是否完成测绘', trigger: 'change' }
        ]
        // actualSurveyTime: [
        //   { required: false, message: '请选择实际测量时间', trigger: 'change' }
        // ],
        // surveyShopArea: [
        //   { required: false, message: '请填写测量卖场面积', trigger: 'change' },
        //   { pattern: /^[0-9]+$/, message: '只能输入数字' }
        // ],
        // ceilingMinHeight: [
        //   { required: false, message: '请填写可吊顶最低高度', trigger: 'change' }
        // ],
        // surveyDheaderArea: [
        //   { required: false, message: '请填写测量门头面积', trigger: 'change' },
        //   { pattern: /^[0-9]+$/, message: '只能输入数字' }
        // ],
        // surveyRefurbishArea: [
        //   { required: false, message: '请填写翻新面积', trigger: 'change' },
        //   { pattern: /^[0-9]+$/, message: '只能输入数字' }
        // ],
        // surveyExpansionArea: [
        //   { required: false, message: '请填写扩建面积', trigger: 'change' },
        //   { pattern: /^[0-9]+$/, message: '只能输入数字' }
        // ],
        // isNeedResurvey: [
        //   { required: true, message: '请选择是否需要复尺', trigger: 'change' }
        // ],
        // unsurveyReason: [
        //   { required: false, message: '请填写未测绘原因', trigger: 'change' }
        // ]
      }
    }
  },
  computed: {
    selectedFileIds() {
      return this.fileList.map(row => {
        return row.id
      })
    }
  },
  watch: {
    //     是否完成测绘为“是”时，
    // 1、实际测量时间、测量卖场面积必填
    // 2、若门店建设范围含门头时，测量门店面积字段必填；若门店建设范围不含门头时，测量门头面积字段隐藏。
    // 3、若门店建设类型含“局部翻新、整体翻新、扩建+翻新”时，测量翻新面积字段必填；若门店建设类型不含“局部翻新、整体翻新、扩建+翻新”时，测量翻新面积字段隐藏。
    // 4、若门店建设类型含”扩建、扩建+翻新“时，测量扩建面积字段必填；若门店建设类型不含”扩建、扩建+翻新“时，测量扩建面积字段隐藏。
    // OVERALL_RENOVATE 整体翻新
    // PARTIAL_RENOVATE 局部翻新
    // EXTEND_RENOVATE 扩建+翻新
    // EXTEND 扩建
    'formData.isFinishMapping': {
      handler(v) {
        if (v === 0) {
          // 未完成测绘
          // this.formRules.actualSurveyTime[0].required = false
          // this.formRules.surveyShopArea[0].required = false
          // this.formRules.ceilingMinHeight[0].required = false
          // this.formRules.surveyDheaderArea[0].required = false
          // this.formRules.surveyRefurbishArea[0].required = false
          // this.formRules.surveyExpansionArea[0].required = false
          // this.formRules.isNeedResurvey[0].required = false
          // this.formRules.unsurveyReason[0].required = true
        } else {
        // 完成测绘
          // this.formRules.actualSurveyTime[0].required = true// 实际测量时间
          // this.formRules.surveyShopArea[0].required = true// 测量卖场面积
          // this.formRules.ceilingMinHeight[0].required = true// 可吊顶最低高度
          this.formData.actualSurveyTime = this.nowTime()
          this.formRuleFormat(this.detailData.decorationRange)

          // this.formRules.isNeedResurvey[0].required = true
          // this.formRules.unsurveyReason[0].required = false
        }
      },
      deep: true,
      immediate: true

    }
  },
  async created() {
    this.id = this.$route.query.id || ''
    if (this.id) {
      this.getFiles()// 获取文件列表信息
      await getDetailData(this.id).then(res => {
        if (res.success === 1) {
          this.detailData = res.data
          this.formRuleFormat(this.detailData.decorationRange)
          const { id, constCode, state, unsurveyReason, isFinishMapping, actualSurveyTime, unresurveyReason, surveyShopArea, surveyDheaderArea, surveyRefurbishArea, surveyExpansionArea, ceilingMinHeight = 0, isNeedResurvey } = res.data
          this.formData = { id, constCode, state, unsurveyReason, isFinishMapping, actualSurveyTime, unresurveyReason, surveyShopArea, surveyDheaderArea, surveyRefurbishArea, surveyExpansionArea, ceilingMinHeight, isNeedResurvey }
        }
      })
    }
  },
  methods: {
    changeMinHeigh(data) {
      const num = Number(data)
      const tem = /^[1-9]\d*\,\d*|[1-9]\d*$/
      if (!tem.test(num) || num <= 0) {
        this.$message.warning('请输入正确的最低吊顶高度')
        return
      }
      this.formData.ceilingMinHeight = Number(data)
    },
    // isDoorInclude 建设范围是否包含门头
    // isNeedRefeshArea 是否需要填写翻新面积
    // isNeedExtendArea 是否需要填写扩建面积
    formRuleFormat(v) {
      this.isDoorInclude = v.includes('DOOR')
      this.isNeedRefeshArea = this.detailData.constType === 'OVERALL_RENOVATE' || this.detailData.constType === 'PARTIAL_RENOVATE' || this.detailData.constType === 'EXTEND_RENOVATE'
      this.isNeedExtendArea = this.detailData.constType === 'EXTEND_RENOVATE' || this.detailData.constType === 'EXTEND'

      // if (this.isDoorInclude) this.formRules.surveyDheaderArea[0].required = true// 测量门头面积
      // else this.formRules.surveyDheaderArea[0].required = false
      // if (this.isNeedRefeshArea) this.formRules.surveyRefurbishArea[0].required = true// 测量翻新面积
      // else this.formRules.surveyRefurbishArea[0].required = false
      // if (this.isNeedExtendArea) this.formRules.surveyExpansionArea[0].required = true// 测量扩建面积
      // else this.formRules.surveyExpansionArea[0].required = false
    },
    changeFile(length) {
      this.fileLength = length
    },
    // 获取附件
    getFiles() {
      getShopAttachment(this.id).then(res => {
        res.data.map(el => {
          if (el.attachmentType === '测绘结果') this.fileDataList.push(el)
          else this.otherFileList.push(el)
        })
        this.fileLength = this.fileDataList.length
      })
    },
    getSelectData(data) {
      if (data) {
        this.fileList = data
      }
    },
    changeShopArea() {
      this.formData.surveyShopArea = (this.formData.surveyExpansionArea || 0) + (this.formData.surveyRefurbishArea || 0)
    },
    // 新增附件
    onSuccess(data) {
      this.fileDataList = [...this.fileDataList, ...data]
      this.refreshFileData()
    },
    // 新增附件上传
    handleAddFile() {
      this.showFileAdd = true
    },

    // 删除附件
    handleDelete() {
      if (!this.singleJudge(this.selectedFileIds, '删除文件', false)) {
        return
      }

      const flag = this.fileDataList.filter(item => {
        const index = this.selectedFileIds.findIndex(i => i === item.id)
        if (index !== -1) this.deleteFile.push({ ...item, dr: 1 })
        return index === -1
      })
      this.fileDataList = flag
    },
    refreshFileData() {
      // 重新请求接口获取附件信息
    },
    // 提交测绘执行数据
    submitForm() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          if (this.formData.isFinishMapping === 1 && this.fileLength === 0) {
            this.$message.warning('请上传测绘结果附件')
            return
          }
          if (this.formData.isFinishMapping === 1) { // 测绘完成时 必须上传测绘结果附件
            this.formData.unsurveyReason = ''
            this.formData.unresurveyReason = !this.formData.isNeedResurvey ? this.formData.unresurveyReason : ''// 是否需要复尺
          } else {
            this.formData.actualSurveyTime = ''
            this.formData.unresurveyReason = ''
            this.formData.surveyShopArea = 0
            this.formData.ceilingMinHeight = 0
            this.formData.surveyDheaderArea = 0
            this.formData.surveyRefurbishArea = 0
            this.formData.surveyExpansionArea = 0
            this.formData.isNeedResurvey = undefined
          }

          this.saveLoading = true
          this.formData.shopAttachmentDTOList = [...this.fileDataList, ...this.otherFileList, ...this.deleteFile]
          saveState(this.formData).then(res => {
            if (res.success === 1) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.$store.dispatch('views/goBack')// 返回列表页
              this.saveLoading = false
            }
          }).catch(() => {
            this.saveLoading = false
          })
        } else {
          this.$message.warning('还有未填报的信息')
        }
      })
    }

  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
</style>
